﻿using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;

public class Pool
{
    Dictionary<string, GameObject> m_Prefabs = new Dictionary<string, GameObject>();
    static Pool instance = null;

    public static Pool GetInstance()
    {
        if (instance == null)
        {
            instance = new Pool();
        }
        return instance;
    }

    private Transform root;
    private Dictionary<string, List<GameObject>> pool = new Dictionary<string, List<GameObject>>();
    private Dictionary<GameObject, string> resMap = new Dictionary<GameObject, string>();

    void InitPool()
    {
        if (root == null)
            root = new GameObject("ObjPool").transform;
    }

    List<GameObject> GetPool(string path)
    {
        InitPool();
        if (!pool.ContainsKey(path))
        {
            pool[path] = new List<GameObject>();
        }
        return pool[path];
    }

    /// <summary>
    /// 同步取obj
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public GameObject GetObj(string path)
    {
        List<GameObject> list = GetPool(path);
        GameObject result = null;
        if (list.Count > 0)
        {
            result = list[list.Count - 1];
            list.RemoveAt(list.Count - 1);
            result.SetActive(true);
        }
        else
        {
            if (!m_Prefabs.ContainsKey(path))
            {
                var prefab = Resources.Load<GameObject>(path);
                if (!prefab)
                {
                    Debug.LogError("Can't found prefab " + path + "In Pool:GetObj");
                    return null;
                }
                m_Prefabs.Add(path, prefab);
            }

            result = GameObject.Instantiate(m_Prefabs[path]);
            if (result)
                resMap[result] = path;
        }
        return result;
    }

    /// <summary>
    /// 销毁或缓存
    /// Tips：没有判断该物体已经在池中，在外面做好处理
    /// </summary>
    /// <param name="go"></param>
    public void DestroyObj(GameObject go)
    {
        string resPath = resMap[go];
        if (string.IsNullOrEmpty(resPath))
        {
            Object.Destroy(go);
            return;
        }
        List<GameObject> list = pool[resPath];
        if (list == null)
        {
            Object.Destroy(go);
            return;
        }
        var tr = go.transform;
        go.SetActive(false);
        //go.name = resPath;
        tr.SetParent(root);
        tr.position = new Vector3(0, 30000, 0);
        list.Add(go);
    }

    public void Clear()
    {
        pool.Clear();
        resMap.Clear();
        if (!root)
            return;
        Object.Destroy(root.gameObject);
        root = null;
    }
}